/**
 * 980. 不同路径 III
 * https://leetcode.cn/problems/unique-paths-iii/description/
 */
class Solution {
    int ret;
    int step;//统计0的个数（要通过的格子）
    int m, n;
    boolean[][] vist;//标记位置是否走过
    public int uniquePathsIII(int[][] grid) {
        m = grid.length; n = grid[0].length;
        vist = new boolean[m][n];
        int x = 0, y = 0;//起始位置
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(grid[i][j] == 0) {
                    step++;
                }
                if(grid[i][j] == 1) {
                    x = i;
                    y = j;
                }
            }
        }
        vist[x][y] = true;
        dfs(grid, x, y, 0);
        return ret;
    }
    //向量数组
    int[] dx = {0, 0, -1, 1};
    int[] dy = {-1, 1, 0, 0};
    public void dfs(int[][] grid, int i, int j, int count) {
        if(grid[i][j] == 2) {
            if((count - 1) == step) ret++;
            return;
        }
        //上下左右四个方向走
        for(int k = 0; k < 4; k++) {
            int x = i + dx[k];
            int y = j + dy[k];
            //判断是否能走
            if(x >= 0 && x < m && y >= 0 && y < n && vist[x][y] == false && grid[x][y] != -1) {
                //可以走
                vist[x][y] = true;
                dfs(grid, x, y, count + 1);
                vist[x][y] = false;//恢复现场
            }
        }
    }
}